package com.cysion.otbox.base

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import com.cysion.otbox.bean.StateEvent
import com.cysion.otbox.ext.logd

abstract class BaseViewModel : ViewModel() {

    private val state = MutableLiveData<StateEvent>()


    internal fun observeState(lifecycleOwner: LifecycleOwner, observer: Observer<StateEvent>) {
        state.observe(lifecycleOwner, observer)
    }

    protected fun postState(aType: String, aMsg: String) {
        logd("flag--postState:type:$aType,msg:$aMsg ")
        val value = state.value ?: StateEvent("200", "")
        value.apply {
            type = aType
            msg = aMsg
        }
        state.value = value
    }

    fun startLoading(msg: String = "") {
        postState(StateEvent.LOADING, msg)
    }

    fun stopLoading() {
        postState(StateEvent.LOADED, "")
    }

    /*发送错误信息，在Ui中的onStateEventChanged()方法接收*/
    fun postError(type: String, msg: String) {
        postState(type, msg)
    }
}
/*当用不到viewmodel时，可用这个*/
class NoViewModel: BaseViewModel()